import { SyntaxHighlighter } from "@renderer/components/business/syntax-highlighter";
import { Button } from "@renderer/components/ui/base/button";
import { Modal } from "@renderer/components/ui/base/modal";
import type { McpServer } from "@shared/triplit/types";
import type { ToolCallResult } from "@shared/types/openai";
import { Check, Clock, RotateCw, X } from "lucide-react";
import { useTranslation } from "react-i18next";

interface ToolCallModalProps {
  isOpen: boolean;
  onClose: () => void;
  toolCall: ToolCallResult;
  mcpServer?: McpServer | null;
  threadId?: string;
  messageId?: string;
}

export function ToolCallModal({
  isOpen,
  onClose,
  toolCall,
  threadId,
  messageId,
}: ToolCallModalProps) {
  const { t } = useTranslation();

  const getStatusIcon = () => {
    switch (toolCall.status) {
      case "success":
        return <div className="h-3 w-3 rounded-full bg-[#38B865]" />;
      case "error":
        return <div className="h-3 w-3 rounded-full bg-[#D82525]" />;
      case "pending":
        return <div className="h-3 w-3 rounded-full bg-[#0056FE]" />;
      default:
        return <Clock className="h-5 w-5 text-gray-400" />;
    }
  };

  const getStatusText = () => {
    switch (toolCall.status) {
      case "success":
        return t("chat.tool-calls.status.success");
      case "error":
        return t("chat.tool-calls.status.error");
      case "pending":
        return t("chat.tool-calls.status.pending");
      default:
        return t("chat.tool-calls.status.unknown");
    }
  };

  const formatArguments = (args: string) => {
    try {
      const parsed = JSON.parse(args);
      return JSON.stringify(parsed, null, 2);
    } catch {
      return args;
    }
  };

  const formatResult = (result: string) => {
    // Try to parse as JSON for better formatting
    try {
      const parsed = JSON.parse(result);
      return JSON.stringify(parsed, null, 2);
    } catch {
      // If not JSON, return as-is
      return result;
    }
  };

  const formatExecutionTime = (time?: number) => {
    if (!time) return "";
    if (time < 1000) return `${time}ms`;
    return `${(time / 1000).toFixed(2)}s`;
  };

  const canApproveReject =
    toolCall.status === "awaiting_approval" && !!threadId && !!messageId;
  const canRerun =
    (toolCall.status === "success" || toolCall.status === "error") &&
    !!threadId &&
    !!messageId;

  const handleApprove = async () => {
    if (!canApproveReject || !threadId || !messageId) return;
    try {
      await window.service.mcpService.approveTool(
        threadId,
        messageId,
        toolCall.id,
      );
    } catch (_error) {}
  };

  const handleReject = async () => {
    if (!canApproveReject || !threadId || !messageId) return;
    try {
      const reason = "User rejected the tool call"; // TODO: 支持输入拒绝原因
      await window.service.mcpService.rejectTool(
        threadId,
        messageId,
        toolCall.id,
        reason,
      );
    } catch (_error) {}
  };

  const handleRerun = () => {
    if (!canRerun || !threadId || !messageId) return;
    onClose();
    void window.service.providerService
      .rerunToolCall(threadId, messageId, toolCall.id)
      .catch(() => {});
  };

  return (
    <Modal isOpen={isOpen} onOpenChange={onClose}>
      <Modal.Content size="4xl" closeButton={false}>
        {() => (
          <>
            <Modal.Header className="hidden">
              <Modal.Title></Modal.Title>
            </Modal.Header>
            <Modal.Body className="px-6 py-4">
              {/* Header with tool name and status */}
              <div className="mb-6 flex items-center justify-between">
                <div>
                  <h3 className="font-medium text-lg text-setting-fg">
                    {toolCall.name}
                  </h3>
                </div>

                <div className="flex items-center gap-2">
                  {getStatusIcon()}
                  <span
                    className={`text-sm ${
                      toolCall.status === "success"
                        ? "text-[#38B865]"
                        : toolCall.status === "error"
                          ? "text-[#D82525]"
                          : toolCall.status === "pending"
                            ? "text-[#0056FE]"
                            : "text-setting-fg"
                    }`}
                  >
                    {getStatusText()}
                  </span>
                  {toolCall.executionTime && (
                    <span className="ml-2 text-muted-fg text-sm">
                      ({formatExecutionTime(toolCall.executionTime)})
                    </span>
                  )}
                </div>
              </div>

              {/* Two-column layout */}
              <div className="grid grid-cols-2 gap-6">
                {/* Left Column: Parameters */}
                <div className="h-[400px] overflow-auto rounded-lg border border-border bg-background">
                  <SyntaxHighlighter
                    language="json"
                    showLineNumbers={false}
                    className="text-sm"
                    title={t("chat.tool-calls.labels.call-parameters")}
                  >
                    {formatArguments(toolCall.arguments)}
                  </SyntaxHighlighter>
                </div>

                {/* Right Column: Result */}
                <div className="h-[400px] overflow-auto rounded-lg border border-border bg-background">
                  {toolCall.status === "success" && toolCall.result && (
                    <SyntaxHighlighter
                      language="json"
                      showLineNumbers={false}
                      className="text-sm"
                      title={t("chat.tool-calls.labels.return-result")}
                    >
                      {formatResult(toolCall.result)}
                    </SyntaxHighlighter>
                  )}

                  {toolCall.status === "error" && toolCall.error && (
                    <div className="p-4">
                      <div className="mb-2 font-medium text-setting-fg text-sm">
                        {t("chat.tool-calls.labels.error-message")}
                      </div>
                      <pre className="whitespace-pre-wrap text-red-600 text-sm">
                        {toolCall.error}
                      </pre>
                    </div>
                  )}

                  {toolCall.status === "pending" && (
                    <div className="flex h-full items-center justify-center">
                      <div className="text-center">
                        <div className="mx-auto mb-2 h-8 w-8 rounded-full bg-[#0056FE]" />
                        <p className="text-[#0056FE] text-sm">
                          {t("chat.tool-calls.status.pending")}
                        </p>
                      </div>
                    </div>
                  )}

                  {toolCall.status === "success" && !toolCall.result && (
                    <div className="flex h-full items-center justify-center">
                      <p className="text-muted-fg text-sm">
                        No result available
                      </p>
                    </div>
                  )}
                </div>
              </div>
            </Modal.Body>
            <Modal.Footer className="px-6 py-4">
              <div className="flex w-full items-center justify-center gap-3">
                {toolCall.status === "awaiting_approval" && (
                  <>
                    <Button
                      intent="primary"
                      onPress={handleApprove}
                      isDisabled={!canApproveReject}
                      className="h-[42px] w-[148px]"
                    >
                      <span data-slot="icon">
                        <Check className="h-4 w-4" />
                      </span>
                      {t("chat.tool-calls.actions.allow")}
                    </Button>
                    <Button
                      intent="danger"
                      onPress={handleReject}
                      isDisabled={!canApproveReject}
                      className="h-[42px] w-[148px]"
                    >
                      <span data-slot="icon">
                        <X className="h-4 w-4" />
                      </span>
                      {t("chat.tool-calls.actions.reject")}
                    </Button>
                  </>
                )}
                {canRerun && (
                  <Button
                    intent="primary"
                    onPress={handleRerun}
                    className="h-[42px] w-[148px]"
                  >
                    <span data-slot="icon">
                      <RotateCw className="h-4 w-4" />
                    </span>
                    {t("chat.tool-calls.actions.rerun")}
                  </Button>
                )}
                <Button
                  intent="outline"
                  onPress={onClose}
                  className="h-[42px] w-[148px]"
                >
                  {t("chat.tool-calls.actions.close")}
                </Button>
              </div>
            </Modal.Footer>
          </>
        )}
      </Modal.Content>
    </Modal>
  );
}
